package com.cenntro.oss.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.cenntro.auth.mapper.SysSooidMapper;
import com.cenntro.auth.model.dbo.SysSooidDO;
import com.cenntro.auth.model.vo.SysSooidAddVO;
import com.cenntro.auth.service.SysSooidService;
import com.cenntro.common.aliyun.FileUpload;
import com.cenntro.common.base.BaseServiceImpl;
import com.cenntro.common.util.ConvertorUtils;
import com.cenntro.common.util.result.Result;
import com.cenntro.oss.common.OssConst;
import com.cenntro.oss.mapper.SysAgentMapper;
import com.cenntro.oss.model.dbo.DevDeviceStaticDO;
import com.cenntro.oss.model.dbo.SysAgentDO;
import com.cenntro.oss.model.vo.AgentTreeVO;
import com.cenntro.oss.model.vo.AgentVO;
import com.cenntro.oss.service.DevDeviceStaticService;
import com.cenntro.oss.service.SysAgentService;
import com.google.common.collect.ImmutableMap;

/**
 * <p>
 * 客户表 服务实现类
 * </p>
 *
 * @author
 * @since 2018-09-13
 */
@Service
public class SysAgentServiceImpl extends BaseServiceImpl<SysAgentMapper> implements SysAgentService {

    @Resource
    private SysSooidService sysSooidService;
    @Resource
    private DevDeviceStaticService devDeviceStaticService;

    @Resource
    private SysSooidMapper sysUserMapper;
    @Resource
    private SysAgentMapper sysAgentMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insert(Object agent) {
        AgentVO vo = (AgentVO) agent;
        // 增加客户
        SysAgentDO sysAgentDO = ConvertorUtils.deepConvert(agent, SysAgentDO.class);
        sysAgentDO.setStatus(1);
        sysAgentDO.setCreateTime(new Date());
        sysAgentDO.setCarNum(0);
        int i = super.insert(sysAgentDO);
       
        
        SysAgentDO p_agent = this.selectById(vo.getPid());
        String agentPath = p_agent == null ? "0_" + sysAgentDO.getId() : p_agent.getAgentPath() + "_" + sysAgentDO.getId();
        sysAgentDO.setAgentPath(agentPath);
        super.update(sysAgentDO);
        if(StringUtils.isNotBlank(vo.getAccount())){
            // 增加客户用户
            SysSooidAddVO sysSooidDO = new SysSooidAddVO();
            sysSooidDO.setUserName(vo.getAccount());
            sysSooidDO.setPassword(vo.getPassword());
            //sysSooidDO.setCdt(new Date());
            //sysSooidDO.setAccountType(OssConstant.ACCOUNT_TYPE_CUSTOMER);
            sysSooidDO.setStatus(1);
            sysSooidDO.setAgentId(sysAgentDO.getId());
            sysSooidDO.setAgentPath(agentPath);
            sysSooidService.insert(sysSooidDO);
            
        }
        return i;
    }

    /**
     * 修改客户
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int update(Object t) {
    	AgentVO agentVO = ConvertorUtils.deepConvert(t, AgentVO.class);
//        AgentVO vo = (AgentVO) t;
        SysAgentDO sysAgentDO = ConvertorUtils.deepConvert(t, SysAgentDO.class);
        sysAgentDO.setUpdateTime(new Date());
        
        Subject subject = SecurityUtils.getSubject(); 
        SysSooidDO user = (SysSooidDO)subject.getPrincipal();
        
        if(agentVO.getPid() != null){
            if(agentVO.getPid() != agentVO.getId()){  //排除选择自己作为父级的可能
                SysAgentDO p_agent = this.selectById(agentVO.getPid());
                String agentPath = p_agent == null ? "0_" + sysAgentDO.getId(): p_agent.getAgentPath() + "_" + sysAgentDO.getId(); 
                sysAgentDO.setAgentPath(agentPath);
                sysAgentDO.setUpdateUser(user.getId().toString());
            }
        }else{
            sysAgentDO.setAgentPath("0_" + sysAgentDO.getId());
            sysAgentDO.setUpdateUser(user.getId().toString());
        }
        
        int i = super.update(sysAgentDO);
        return i;
    }

    /**
     * 删除客户，以及客户帐号
     * 
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteById(Integer id) {
        DevDeviceStaticDO dsd = new DevDeviceStaticDO();
        dsd.setAgentId(id);
        int count = devDeviceStaticService.selectCount(dsd);
        Assert.isTrue(count <= 0, "请删除客户下的车辆");

        SysAgentDO agent = this.selectById(id);
        SysAgentDO agentDO = new SysAgentDO();
        agentDO.setStatus(1);
        agentDO.setAgentPath(agent.getAgentPath());
        List<SysAgentDO> agentList = this.selectPage(agentDO);
        if (CollectionUtils.isNotEmpty(agentList) && agentList.size() > 2) {
            Assert.isTrue(count <= 0, "请删除客户下子组织");
        }

        SysSooidDO sooid = new SysSooidDO();
        sooid.setAgentPath(agent.getAgentPath());
        sooid.setStatus(1);
        List<SysSooidDO> sooidList = sysSooidService.selectPage(sooid);
        sooidList.forEach(e -> {
            if (!e.getAgentPath().equals(agent.getAgentPath())) {
                Assert.isTrue(count <= 0, "请删除客户下员工");
            } else {
                SysSooidAddVO  sooidVO = new SysSooidAddVO();
                sooidVO.setId(e.getId());
                sooidVO.setStatus(-1);
                sysSooidService.update(sooidVO);
            }
        });
        SysAgentDO sysAgentDO = new SysAgentDO();
        sysAgentDO.setId(id);
        sysAgentDO.setStatus(-1);
        int i = super.update(sysAgentDO);
        sysAgentDO = super.selectById(id);
        return i;
    }
    
    /**
     * agentId转换agentPath
     * @param agentId
     * @return
     */
    public String agentIdConvertAgentPath(Integer agentId) {
		if (agentId != null) {
			String agentPath = "";
			SysAgentDO agent = sysAgentMapper.selectById(agentId);
			if (agent != null) {
				if (StringUtils.isNoneBlank(agent.getAgentPath())) {
				    agentPath = agent.getAgentPath();
					//agentPath = agent.getAgentPath() + "-" + agent.getId();
				} else {
					agentPath = OssConst.ROOT_ID + OssConst.DIVIDING_LINE + agent.getId();
				}
				return agentPath;
			}
		}
		return null;

	}
    

    @Override
    public List<AgentTreeVO> agentTree(Integer agentId) {
        List<AgentTreeVO> listVO = new ArrayList<>();
        SysAgentDO agent = sysAgentMapper.selectById(agentId);
        String path = "";
        if (agent != null) {
            AgentTreeVO tree = new AgentTreeVO();
            tree.setId(agent.getId());
            tree.setCompany(agent.getCompany());
            path = agent.getAgentPath() + "-" + agent.getId();
            tree.setAgentPath(agent.getAgentPath());
            tree.setNextLevel(nextLevel(path));
            listVO.add(tree);
        }
        return listVO;
    }

    private List<AgentTreeVO> nextLevel(String path) {
        List<AgentTreeVO> listVO = new ArrayList<>();
        List<SysAgentDO> list = sysAgentMapper.selectByMap(ImmutableMap.of("agentPath", path));
        if (list != null && list.size() > 0) {
            for (SysAgentDO agent : list) {
                AgentTreeVO tree = new AgentTreeVO();
                path = agent.getAgentPath() + "-" + agent.getId();
                tree.setId(agent.getId());
                tree.setCompany(agent.getCompany());
                tree.setAgentPath(agent.getAgentPath());
                tree.setNextLevel(nextLevel(path));
                listVO.add(tree);
            }
        }
        return listVO;

    }


    @Override
    public Result updateLogo(Integer agentId, HttpServletRequest request) {
        SysAgentDO agent = sysAgentMapper.selectById(agentId);
        String logo = null;
        if (agent != null) {
            FileUpload file = new FileUpload();
            try {
                logo = file.upload(request);
                agent.setLogo(logo);
                sysAgentMapper.update(agent);
                //删除历史图片
                file.deleteFile(agent.getLogo());
                agent.setLogo(logo);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Result.ok(logo);
    }
    
}
